import { defineStore } from "pinia";

export const useAuthStore = defineStore("authStore", {
  state: () => ({
    token: null,
    user: null,
    errors: {},
  }),
  getters: {
    isAuthenticated: (state) => !!state.token,
  },
  actions: {
    /************************获取用户*********************************/
    async getUser() {
      if (localStorage.getItem("token")) {
        console.log(this.token);

        const res = await fetch("/api/user", {
          headers: {
            Authorization: `Bearer ${localStorage.getItem("token")}`,
          },
        });
        const data = await res.json();
        if (res.ok) {
          this.user = data;
        }
      }
    },
    /************************Login/Register***************************/
    async authenticate(url, formData) {
      const res = await fetch(`/api/${url}`, {
        method: "POST",
        body: JSON.stringify(formData),
      });
      const data = await res.json();
      if (data.errors) {
        this.errors = data.errors;
      } else {
        localStorage.setItem("token", data.token);
        this.token = data.token;
        this.user = data.user;
        this.router.push({ name: "home" });
      }
    },
    /************************Logout***************************/
    async logout() {
      const res = await fetch("/api/logout", {
        method: "POST",
        headers: {
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      });
      const data = await res.json();
      if (res.ok) {
        this.token = null;
        this.user = null;
        this.errors = null;
        localStorage.removeItem("token");
        this.router.push({ name: "home" });
      }
    },
  },
});
